package org.javaboy.encrypt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

public class EncryptEnvPostProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        //这是读取所有的配置文件
        MutablePropertySources propertySources = environment.getPropertySources();
        Map<String, Object> decryptMap = new HashMap<>();
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource instanceof MapPropertySource map) {
                //获取配置中属性的名称
                String[] propertyNames = map.getPropertyNames();
                for (String propertyName : propertyNames) {
                    //拿到具体的 value  db.password={cipher}root
                    Object value = map.getProperty(propertyName);
                    if (value instanceof String val) {
                        if (val.startsWith("{cipher}")) {
                            //说明是一个密文，需要解密
                            String decryptStr = AesUtils.decrypt(val.replace("{cipher}", ""));
                            decryptMap.put(propertyName, decryptStr);
                        }
                    }
                }
            }
        }
        //将解密的内容放到前面，相当于覆盖了未解密的字符串
        propertySources.addFirst(new MapPropertySource("decrypt", decryptMap));
    }
}
